<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input
          v-model="queryParams.keyword"
          style="margin-bottom: 10px;"
          type="text"
          prefix-icon="el-icon-search"
          @input="changeValue"
        />
        <!-- 树形结构
          current-change 当前选中节点变化是触发的事件
          setCurrentKey 通过key设置某个节点的当前选中状态 使用刺方法必须设置 node-key 属性
        -->
        <el-tree
          ref="deptTree"
          :data="departmentList"
          :props="defaultProps"
          :expand-on-click-node="false"
          default-expand-all
          highlight-current
          node-key="id"
          @current-change="selectNode"
        />
      </div>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>
          <el-button size="mini" @click="showExcelDialog=true">excel导入</el-button>
          <el-button size="mini" @click="exportEmployee">excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table :data="employeeList">
          <el-table-column align="center" label="头像" prop="staffPhoto">
            <template v-slot="{row}">
              <el-avatar v-if="row.staffPhoto" :src="row.staffPhoto" :size="40" />
              <span v-else class="username">{{ row.username.charAt(0) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="手机号" sortable prop="mobile" />
          <el-table-column label="工号" sortable prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template v-slot="{row}">
              <span v-if="row.formOfEmployment===1">正式</span>
              <span v-else-if="row.formOfEmployment===2">非正式</span>
              <span v-else>无</span>
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" sortable prop="timeOfEntry" />
          <el-table-column label="操作" width="200px">
            <template v-slot="{row}">
              <el-button type="text" size="mini" @click="$router.push('/employee/detail/'+row.id)">查看</el-button>
              <el-button type="text" size="mini">角色</el-button>
              <el-popconfirm title="您确定要删除当前员工吗?" @onConfirm="del(row.id)">
                <el-button slot="reference" type="text" size="mini" style="margin-left: 10px;">删除</el-button>
              </el-popconfirm>

            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row align="middle" type="flex" justify="end" style="height: 60px;">
          <el-pagination
            layout=" total, prev, pager, next"
            :total="total"
            :current-page="queryParams.page"
            :page-size="queryParams.pagesize"
            @current-change="changePage"
          />
        </el-row>
      </div>
    </div>
    <!-- 放置导入组件 -->
    <import-excel :show-excel-dialog.sync="showExcelDialog" @uploadSuccess="getEmployeeList" />
  </div>
</template>
<script>
import { getDepartment } from '@/api/department'
import { getEmployeeList, exportEmployee, delEmployee } from '@/api/employee'
import { transListToTreeDate } from '@/utils'
import FileSaver from 'file-saver'
import ImportExcel from './components/import-excel.vue'
export default {
  name: 'Employee',
  components: {
    ImportExcel
  },
  data() {
    return {
      showExcelDialog: false,
      departmentList: [], // 组织数据
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      // 存储查询参数
      queryParams: {
        departmentId: null, // 记录部门id
        page: 1, // 当前页码
        pagesize: 11,
        keyword: ''
      },
      total: 0, // 记录员工的总数
      employeeList: [] // 存储员工列表数据
    }
  },
  created() {
    this.getDepartment()
  },
  methods: {
    async del(id) {
      await delEmployee(id)

      if (this.employeeList.length === 1 && this.queryParams.page > 1) {
        // 先返回当前值 然后减去1 返回的是旧值
        this.queryParams.page--
        // 当前的值减去1 并将结果赋值给页码, 返回的是新值
        // this.queryParams.page -= 1
      }
      this.$message.success('删除成功')
      this.getEmployeeList()
    },
    async exportEmployee() {
      // console.log('导出')
      const res = await exportEmployee() // 导出所有的员工接口
      // debugger
      // console.log(res.headers)
      console.log('贱人恒') // 使用一个npm包 直接将blob 文件下载到本地 file-saver
      // FileSaver.saveAs(blob对象, 文件名称)
      FileSaver.saveAs(res, '员工信息表.xlsx') // 下载文件
    },
    async getDepartment() {
      // 递归方法 将列表转化成树形
      this.departmentList = transListToTreeDate(await getDepartment(), 0)
      // console.log(this.departmentList[0])
      this.queryParams.departmentId = this.departmentList[0].id // 记录首个节点id
      // 设置选中的节点
      // 树组件渲染是异步的 等到更新完毕
      this.$nextTick(() => {
        // 此时意味着数渲染完毕
        this.$refs.deptTree.setCurrentKey(this.queryParams.departmentId)
      })
      // this.$refs.deptTree.setCurrentKey(this.queryParams.departmentId)
      // 这个时候已经拿到参数 记录了id
      this.getEmployeeList()
    },
    selectNode(node) {
      // console.log(node)
      this.queryParams.departmentId = node.id // 重新记录了参数
      this.queryParams.page = 1
      this.getEmployeeList()
    },
    // 获取员工列表的方法
    async getEmployeeList() {
      const { rows, total } = await getEmployeeList(this.queryParams)
      // console.log(rows)
      const processedRows = rows.map(item => ({
        ...item,
        username: item.username.split('黑马').join('')
      // name: item.username.replace('黑马', '')
      }))

      this.employeeList = processedRows
      this.total = total
    },
    // 切换页码事件
    changePage(newPage) {
      this.queryParams.page = newPage // 赋值新页码
      this.getEmployeeList()// 查询参数
    },
    // 输入框事件,输入值就会触发
    changeValue() {
      // console.log(this.queryParams.keyword)
      // 防抖   单位时间内只执行一次
      // this 的实例上赋值了一个timer 的属性
      clearTimeout(this.timer) // 清理上一次的定时器
      this.timer = setTimeout(() => {
        this.queryParams.page = 1
        this.getEmployeeList()
      }, 500)
    }
  }
}
</script>
<style lang="scss" scoped>
.app-container {
  display: flex;
  background: #fff;

  .left {
    width: 280px;

    padding: 20px;
    border-right:1px solid #eaeef4;
  }
  .right {
    flex: 1;

    padding: 20px;
    .opeate-tools {
      margin: 10px;
    }
    .username{
      width: 30px;
      height: 30px;
      line-height: 30px;
      border-radius: 50%;
      text-align: center;
      background: #409eff;
      color: #fff;
      display: inline-block;
      font-size: 12px;
    }
  }
}
</style>
